<template>
  <q-dialog v-model="show" @hide="handleClose">
    <q-card style="min-width: 600px; max-width: 700px; max-height: 80vh">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">账号设置</div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section class="q-pt-none">
        <q-tabs v-model="tab" dense class="text-grey" active-color="primary" indicator-color="primary" align="left">
          <q-tab name="account" label="账号" icon="person" />
          <q-tab name="privacy" label="隐私" icon="lock" />
          <q-tab name="notifications" label="通知" icon="notifications" />
        </q-tabs>
        <q-separator />
      </q-card-section>

      <q-card-section class="q-pt-none" style="max-height: calc(80vh - 150px); overflow-y: auto">
        <!-- 账号设置 -->
        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="account">
            <div class="text-h6 q-mb-md">账号信息</div>
            <q-form @submit="handleSaveAccount" class="q-gutter-md">
              <q-input
                :model-value="currentUser?.email"
                label="邮箱"
                outlined
                readonly
                hint="邮箱不可修改"
              />
              <q-input
                v-model="accountForm.name"
                label="昵称"
                outlined
                autocomplete="off"
                :rules="[val => !!val || '请输入昵称', val => val.length <= 20 || '昵称不能超过20个字符']"
              />
              <q-input
                v-model="accountForm.phone"
                label="手机号"
                outlined
                autocomplete="off"
                :rules="[val => !val || /^1[3-9]\d{9}$/.test(val) || '请输入正确的手机号']"
              />
              <q-select
                v-model="accountForm.gender"
                :options="genderOptions"
                label="性别"
                outlined
                emit-value
                map-options
              />
              <q-btn
                flat
                label="保存"
                color="primary"
                @click="handleSaveAccount"
                :loading="savingAccount"
                class="q-mt-md"
              />
            </q-form>
          </q-tab-panel>

          <!-- 隐私设置 -->
          <q-tab-panel name="privacy">
            <div class="text-h6 q-mb-md">隐私设置</div>
            <div class="q-gutter-md">
              <q-toggle
                v-model="privacyForm.showPhone"
                label="允许他人查看我的手机号"
                color="primary"
              />
              <q-toggle
                v-model="privacyForm.showEmail"
                label="允许他人查看我的邮箱"
                color="primary"
              />
              <q-toggle
                v-model="privacyForm.allowFriendRequest"
                label="允许他人添加我为好友"
                color="primary"
              />
              <q-btn
                flat
                label="保存"
                color="primary"
                @click="handleSavePrivacy"
                :loading="savingPrivacy"
                class="q-mt-md"
              />
            </div>
          </q-tab-panel>

          <!-- 通知设置 -->
          <q-tab-panel name="notifications">
            <div class="text-h6 q-mb-md">通知设置</div>
            <div class="q-gutter-md">
              <q-toggle
                v-model="notificationForm.enableMessageSound"
                label="消息提示音"
                color="primary"
              />
              <q-toggle
                v-model="notificationForm.enableDesktopNotification"
                label="桌面通知"
                color="primary"
              />
              <q-toggle
                v-model="notificationForm.enableFriendRequestNotification"
                label="好友请求通知"
                color="primary"
              />
              <q-toggle
                v-model="notificationForm.enableGroupNotification"
                label="群组消息通知"
                color="primary"
              />
              <q-select
                v-model="notificationForm.dndStartTime"
                label="免打扰开始时间"
                outlined
                :options="timeOptions"
                emit-value
                map-options
              />
              <q-select
                v-model="notificationForm.dndEndTime"
                label="免打扰结束时间"
                outlined
                :options="timeOptions"
                emit-value
                map-options
              />
              <q-btn
                flat
                label="保存"
                color="primary"
                @click="handleSaveNotifications"
                :loading="savingNotifications"
                class="q-mt-md"
              />
            </div>
          </q-tab-panel>
        </q-tab-panels>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { getUser, updateUserProfile, User } from '../services/auth'
import { useQuasar } from 'quasar'

const props = defineProps<{
  modelValue: boolean
  initialTab?: 'account' | 'privacy' | 'notifications'
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'updated': []
}>()

const $q = useQuasar()
const show = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
})

const tab = ref<'account' | 'privacy' | 'notifications'>(props.initialTab || 'account')
const currentUser = ref<User | null>(null)
const savingAccount = ref(false)
const savingPrivacy = ref(false)
const savingNotifications = ref(false)

const accountForm = ref({
  name: '',
  phone: '',
  gender: 3,
})

const privacyForm = ref({
  showPhone: false,
  showEmail: false,
  allowFriendRequest: true,
})

const notificationForm = ref({
  enableMessageSound: true,
  enableDesktopNotification: true,
  enableFriendRequestNotification: true,
  enableGroupNotification: true,
  dndStartTime: '22:00',
  dndEndTime: '08:00',
})

const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 },
  { label: '未知', value: 3 },
]

const timeOptions = Array.from({ length: 24 }, (_, i) => {
  const hour = String(i).padStart(2, '0')
  return { label: `${hour}:00`, value: `${hour}:00` }
})

watch(() => props.modelValue, (val) => {
  if (val) {
    // 设置初始标签页
    if (props.initialTab) {
      tab.value = props.initialTab
    }
    currentUser.value = getUser()
    accountForm.value = {
      name: currentUser.value?.name || '',
      phone: currentUser.value?.phone || '',
      gender: currentUser.value?.gender || 3,
    }
    // 从 localStorage 加载隐私和通知设置（如果存在）
    const privacySettings = localStorage.getItem('privacySettings')
    if (privacySettings) {
      try {
        Object.assign(privacyForm.value, JSON.parse(privacySettings))
      } catch (e) {
        // 忽略解析错误
      }
    }
    const notificationSettings = localStorage.getItem('notificationSettings')
    if (notificationSettings) {
      try {
        Object.assign(notificationForm.value, JSON.parse(notificationSettings))
      } catch (e) {
        // 忽略解析错误
      }
    }
  }
})

watch(() => props.initialTab, (newTab) => {
  if (newTab && props.modelValue) {
    tab.value = newTab
  }
})

const handleSaveAccount = async () => {
  if (!accountForm.value.name) {
    $q.notify({
      type: 'negative',
      message: '请输入昵称',
    })
    return
  }

  savingAccount.value = true
  try {
    const updateData: any = {
      name: accountForm.value.name,
      gender: accountForm.value.gender,
    }
    
    if (accountForm.value.phone !== undefined) {
      updateData.phone = accountForm.value.phone || ''
    }
    
    const updatedUser = await updateUserProfile(updateData)
    localStorage.setItem('user', JSON.stringify(updatedUser))
    currentUser.value = updatedUser
    
    $q.notify({
      type: 'positive',
      message: '保存成功',
    })

    emit('updated')
  } catch (error: any) {
    $q.notify({
      type: 'negative',
      message: error.message || '保存失败',
    })
  } finally {
    savingAccount.value = false
  }
}

const handleSavePrivacy = async () => {
  savingPrivacy.value = true
  try {
    // 保存到 localStorage（实际应用中应该保存到服务器）
    localStorage.setItem('privacySettings', JSON.stringify(privacyForm.value))
    
    $q.notify({
      type: 'positive',
      message: '隐私设置已保存',
    })
  } catch (error: any) {
    $q.notify({
      type: 'negative',
      message: error.message || '保存失败',
    })
  } finally {
    savingPrivacy.value = false
  }
}

const handleSaveNotifications = async () => {
  savingNotifications.value = true
  try {
    // 保存到 localStorage（实际应用中应该保存到服务器）
    localStorage.setItem('notificationSettings', JSON.stringify(notificationForm.value))
    
    $q.notify({
      type: 'positive',
      message: '通知设置已保存',
    })
  } catch (error: any) {
    $q.notify({
      type: 'negative',
      message: error.message || '保存失败',
    })
  } finally {
    savingNotifications.value = false
  }
}

const handleClose = () => {
  show.value = false
}
</script>

<style scoped>
</style>

